package com.example.demo2Jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet("/addbook")
public class AddBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8"); //解决客 户端向服务器端传递中文数据的乱码问题
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        int price = Integer.parseInt(req.getParameter("price"));
        //1.加载JDBC驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获得数据库连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC", "root", "root");
            //3.执行SQL语句，实现增、删、改、查操作
            String sql = "insert into book(title, author, price) values(?, ?, ?) "; //①创建SQL语句，带?占位符
            PreparedStatement pstmt = conn.prepareStatement(sql); // ②创建PreparedStatement对象
            pstmt.setString(1, title); //③给?占位符赋值，数字表示SQL语句中占位符序号
            pstmt.setString(2, author);
            pstmt.setInt(3, price);
            int count = pstmt.executeUpdate(); //④执行 SQL语句，返回受影响的行数
            if (count > 0) { //4. 结果处理。根据受影响的行数是否大于0，可以判断执行成功与否
                resp.sendRedirect("getbook");
            }
            pstmt.close();
            conn.close(); //5.关闭连接
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}



